<template>
	<view class="root">
		<view v-if="loaded" :class="hasComment ? 'blog-container' : 'blog-margin-container'">
			<text class="blog-title">{{blog.title}}</text>
			<text class="blog-author">{{blog.user.nickName}} @ {{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="blog-content"></rich-text>
			<image :src="blog.picture" mode="widthFix" class="img item-pic"></image>
			<view>
				<text v-for="(tag,idx) in blog.tags" :key="idx" class="item-tag">{{tag}}</text>
			</view>
			<image :src="blog.user.avatar" mode="aspectFill" class="img-head"></image>
			<view class="icon_container">
				<image @click="changeGood(blog.id,true)" v-if="good_ids.indexOf(blog.id) < 0"
					src="../../static/icons/ic_good_fill.png" class="icon"></image>
				<image @click="changeGood(blog.id,false)" v-else src="../../static/icons/ic_good.png" class="icon">
				</image>
				<text class="icon-text">{{blog.good}}</text>
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
		</view>


		<view v-if="hasComment" class="blog-containner">
			<view v-for="(item,index) in parents" :key="item.id">
				<view class="parent-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<view class="cmt-time-container">
						<text class="cmt-time">{{item.createTime}}</text>
						<text v-if="canDelete(item)" class="txt-delete" @click="deleteCmt(item,true,index)">[删除]</text>
					</view>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
				</view>


				<view v-if="replies[index].length > 0" class="replies-container">
					<view v-for="(reply,idx) in replies[index]" :key="reply.id" class="reply-item">
						<view class="reply-info">
							<text class="reply-author">{{reply.nickName}}:</text>
							<text class="reply-to">@{{reply.toUser}}</text>
							<text class="reply-tiem">{{reply.createTime}}</text>
							<text v-if="canDelete(reply)" class="txt-delete"
								@click.stop="deleteCmt(reply,false,index)">[删除]</text>
						</view>
						<text class="reply-content" @click="clickToReply(reply)"> {{reply.content}}</text>
					</view>
				</view>
				<view v-if=" index < parents.length -1" class="cmt-line"></view>
			</view>
		</view>
		<view class="input-container">
			<image :src="userAvatar" mode="aspectFill" class="input-avatars" @click="clickLogin"></image>
			<!-- 添加单击事件，弹出login -->
			<textarea auto-height v-model="inputValue" :placeholder="inputHoldr" class="input-area"
				placeholder-class="input-older" @input="inputGetValue" />
			<image src="../../static/icons/commit.png" class="input-commit" @click="clickCommit"></image>
		</view>
		<!-- 登录组件 -->
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>
<script>
	// let key_goods = 'goods'
	let parentId = null
	let cmtValue = ""
	// let key_goods = "good_ids"
	let app = getApp()
	export default {
		data() {
			return {
				blog: [],
				good_ids: [],
				hasGood: false,
				loaded: false,
				parents: [], //父评论
				replies: [], //子评论
				hasComment: false,
				inputValue: "",
				inputHoldr: "请输入评论内容....",
				userAvatar: "../../static/icons/default_user.png"
			}
		},
		//加载时执行
		onLoad(options) {
			let id = options.id
			let good_ids = uni.getStorageSync(this.$params.key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			this.addReadCount(id)
			this.$noti.add(this.$params.noti_login_status,this.afterLogin,this)
		},
		onunload(){
			this.$noti.remove(this.$params.noti_login_status,this)
		},

		methods: {
			//登录
			clickLogin() {
				this.$refs.login.show()
			},
			changeGood(id, hasGood) {
				//同步到服务器,并且去最新数据
				let url = this.$params.host
				let action = hasGood ? this.$params.action_good : this.$params.action_del_good
				url += action
				let data = {
					"id": id
				}
				this.$request.postParam(url, data, res => {
					this.blog.good = res.data
					if (hasGood) {
						this.good_ids.push(id);
						// this.good_ids = this.good_ids.concat(id)
					} else {
						let index = this.good_ids.indexOf(id);
						this.$utli.remove(this.good_ids, index)
					}
					uni.setStorageSync(this.$params.key_good_ids, this.good_ids);
				}, () => {})
			},

			addReadCount(id) {
				let url = this.$params.host + this.$params.action_read_count
				let data = {
					"id": id
				}
				this.$request.postParam(url, data, res => {
					let count = res.data
					//第一种方式获取上一页面实例
					// this.refreshPreviousPage(id,count)
					//使用通知中心解耦
					this.$noti.post(this.$params.$noti_refresh_count, {
						id,
						count
					})
				}, () => {
					this.getBlog(id)
					// console.log(id);
				})
			},
			//获取上一页的实例作为
			refreshPreviousPage(id, count) {
				let pages = getCurrentPages()
				let prev = pages[pages.length - 2]
				prev.refreshReadCount(pages, prev)
			},

			getBlog(id) {
				let url = this.$params.host + this.$params.action_blog + id
				this.$request.get(url, res => {
					this.loaded = true
					let blog = res.data
					this.hasComment = blog.comments.length > 0
					uni.setNavigationBarTitle({
						title: blog.user.nickName,
					})
					if (!blog.picture.startsWith("http")) {
						blog.picture = this.$params.host + blog.picture
					}
					blog.user.avatar = this.$params.host + blog.user.avatar
					blog.content = blog.content.replace(/\<img/gi, '<img class="img" ')
					blog.createTime = this.$utli.formatTime(new Date(blog.createTime))
					this.blog = blog
					//
					this.formatComment(this.blog.comments)
					// console.log(blog);
					// console.log(blog.user.avatar);

				}, () => {})
			},

			formatComment(comments) {
				if (comments.length == 0) {
					return
				}
				let rootComments = []///http:/1.12.223.54/a.jpg
				comments.forEach(c => {
					if (!c.avatar.startsWith("/http")) {
						c.avatar = c.avatar.substring(1)
					}else {
						c.avatar=this.$params.host+c.avatar.substring(1)
					}
					c.createTime = this.$utli.formatTime(new Date(c.createTime))
					if (c.parentId == null) {
						rootComments.push(c)
					}
				})
				// 降序排列
				rootComments.sort((c1, c2) => {
					return new Date(c2.createTime).getTime() - new Date(c1.createTime).getTime()
				})

				let replies = new Array(rootComments.length).fill([])
				let index = 0
				rootComments.forEach(r => {
					let cmmts = []
					cmmts = cmmts.concat(this.getChildren(r, comments))
					replies[index++] = cmmts
					// 寻找不同子评论的评论（过滤相同的评论）
					comments = comments.filter(c => cmmts.every(cc => cc.id != c.id))
				})

				// if(rootComments.blogId == this.blog.id){
				// 	this.parents = rootComments
				// }
				this.parents = rootComments
				this.replies = replies
				console.log(rootComments)
				console.log(replies)
			},
			getChildren(parent, comments) {
				// todo：得到parent所有的子评论
				let childrenComments = [];
				comments.forEach(comment => {
					if (parent.id == comment.parentId) {
						comment.toUser = parent.nickName
						childrenComments.push(comment);
						// 过滤相同的评论
						let cmmts = comments.filter(cmt => cmt.id != comment.id)
						childrenComments.concat(this.getChildren(comment, comments))
					}
				})
				return childrenComments;

			},
			canDelete(item) {
				return app.globalData.type == 1 || item.avatar || this.userAvatar
			},
			// 删除评论
			deleteCmt(cmt, isParent, index) {
				let url = this.$params.host + this.$params.action_delete_comment + cmt.id
				let data = {
					token: app.globalData.token
				}
				uni.showModal({
					title: '删除评论',
					content: '确认删除评论吗',
					showCancel: true,
					cancelText: '算了',
					confirmText: '删除',
					success: res => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除评论...',
								mask: false
							});
							this.$request.deleteParams(url, data, res => {
								uni.showToast({
									title: res.message,
									icon: 'none'
								});
								if (res.success) {
									if (isParent){
										let list=this.replies[index]
										list.push(this.parents[index])
										this.$utli.remove(this.parent,index)
										this.$utli.remove(this.replies,index)
										this.blog.comments=this.blog.comments.filter(c =>list.every(r =>r.id != c.id))
									}else{
										let children =this.getChildren(cmt,this.replies[index])
										children.push(cmt)
										this.replies[index]=this.replies[index].filter(r =>children.every(c => c.id!= r.id))
										this.blog.comments=this.blog.comments.filter(c =>children.every(r =>r.id != c.id))
									}
								}
							}, () => {
								uni.hideLoading()
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},

			clickToReply(item) {
				parentId = item.id
				this.inputHoldr = "@" + item.nickName
			},
			inputGetValue(e) {
				cmtValue = e.detail.value
				// console.log(cmtValue);
			},
			// 更换图片
			afterLogin() {
				this.userAvatar = this.$params.host + getApp().globalData.avatar
				// console.log(userAvatar)
			},
			clickCommit() {
				//1.判断是否登录
				if (app.globalData.token.length == 0) {
					console.log(cmtValue)
					this.$refs.login.show()
					return
				}
				// 2.判断数据非空合法性
				if (cmtValue.length == 0) {
					uni.showToast({
						title: '请输入数据',
						icon: 'none'
					});
					return
				}
				//3.发请求
				let url = this.$params.host + this.$params.action_add_comment
				let data = {
					nick_name: app.globalData.nickName,
					avatar: "/" + app.globalData.avatar,
					email: app.globalData.email,
					content: cmtValue,
					blog_id: this.blog.id,
					parent_id: parentId,
					token: app.globalData.token,
					is_owner: app.globalData.uid == this.blog.user.id
				}
				this.$request.post(url, data, res => {
					//4.刷新评论数据
					// console.log(res)
					if (!res.success) {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
						return
					}
					let cmt = {}
					cmt.avatar = res.data.avatar
					cmt.blogId = res.data.blogId
					cmt.content = res.data.content
					cmt.createTime = res.data.createTime
					cmt.email = res.data.email
					cmt.id = res.data.id
					cmt.nickName = res.data.nickName
					cmt.owner = res.data.owner
					cmt.parentId = res.data.parentId
					let comments = this.blog.comments.concat(cmt)
					this.blog.comments = comments
					this.formatComment(comments)
					this.hasComment = this.blog.comments.length > 0
					this.inputHoldr = "请输入评论....."
					this.inputValue = ""
					cmtValue = ""
					parentId = null
					//刷新列表页的评论
					let comment = this.blog.comments
					let id = this.blog.id
					this.$noti.post(this.$params.noti_refresh_comment, {
						id,
						comment,
					})
				}, () => {})

			}
		}
	}
</script>

<style>
	@import url("blog.css");
</style>
